package com.example.park_2306.fg

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.provider.MediaStore.Video
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.example.base.entity.AgreeEntity
import com.example.base.entity.CommentEntity
import com.example.base.entity.CommentEntityItem
import com.example.base.entity.TypeEntity
import com.example.base.entity.VideoEntity
import com.example.base.mvi.BaseFragment
import com.example.base.mvi.HttpType
import com.example.base.mvi.UiState
import com.example.base.param.Reply
import com.example.base.param.SendComment
import com.example.base.utils.DateTimeUtils
import com.example.base.utils.GlideUtils
import com.example.park_2306.R
import com.example.park_2306.adapter.CommentAdapter
import com.example.park_2306.adapter.TypeAdapter
import com.example.park_2306.adapter.VideoAdapter
import com.example.park_2306.databinding.FragmentHomeBinding
import com.example.park_2306.video.VideoIntent
import com.example.park_2306.video.VideoViewModel
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
import com.wildma.pictureselector.PictureBean
import com.wildma.pictureselector.PictureSelector
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
class HomeFragment : BaseFragment<FragmentHomeBinding,VideoIntent,VideoViewModel>() {

    val typeAdapter by  lazy { TypeAdapter() }
    val videoAdapter by lazy { VideoAdapter() }
    val commentAdapter by lazy { CommentAdapter() }

    var channelId = "94349546935"
    var page = 1
    var size = 10
    var index = -1//当前展示下标

    var loveFlag = false//当前视频是否点赞了  默认未点赞
    lateinit var agreeEntity: AgreeEntity
    override fun getLayout(): Int  = R.layout.fragment_home

    override fun getVM(): Class<VideoViewModel>  = VideoViewModel::class.java

    override fun initView() {
        binding.iv.setOnClickListener {
            PictureSelector.create(this,100).selectPicture()
        }



        binding.rvType.apply {
            adapter = typeAdapter
            layoutManager = LinearLayoutManager(requireContext(),LinearLayoutManager.HORIZONTAL,false)
        }
        var layoutManager = LinearLayoutManager(requireContext())
        binding.rvVideo.adapter = videoAdapter
        binding.rvVideo.layoutManager = layoutManager
        //请求数据
        viewModel.sendIntent(VideoIntent.videoType)

        viewModel.sendIntent(VideoIntent.video(channelId,page,size))

        //点击进行切换
        typeAdapter.setOnItemClickListener { adapter, view, position ->
            channelId = typeAdapter.data[position].channelid
            page = 1
            typeAdapter.setId(channelId)
            viewModel.sendIntent(VideoIntent.video(channelId,page,size))
        }
        //刷新加载更多
        binding.smart.setOnRefreshLoadMoreListener(object:OnRefreshLoadMoreListener{
            override fun onRefresh(refreshLayout: RefreshLayout) {
                page = 1
                viewModel.sendIntent(VideoIntent.video(channelId,page,size))
                binding.smart.finishRefresh()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                page++
                viewModel.sendIntent(VideoIntent.video(channelId,page,size))
                binding.smart.finishLoadMore()
            }
        })
        //仿抖音滑动分页
        val pagerSnapHelper = PagerSnapHelper()
        pagerSnapHelper.attachToRecyclerView(binding.rvVideo)
        //自动播放
        binding.rvVideo.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
            //找到当前显示的第一个可见的小标
            index = layoutManager.findFirstVisibleItemPosition()
            val player =
                videoAdapter.getViewByPosition(index, R.id.gsy) as StandardGSYVideoPlayer
            player.startPlayLogic()
            loveFlag = false
            viewModel.sendIntent(VideoIntent.queryById(videoAdapter.data[index].id))
        }
        //点击点赞图标 ，实现点赞取消点赞
        videoAdapter.addChildClickViewIds(R.id.video_love,R.id.video_comment,R.id.comment_close,R.id.video_star,R.id.comment_send_btn)
        videoAdapter.setOnItemChildClickListener { adapter, view, position ->
            when(view.id){
                R.id.video_love->{
                    love(position)
                }
                R.id.video_comment->{
                    binding.rvVideo.setFlag1(false)
                    openComment(position)
                }
                R.id.comment_close->{
                    binding.rvVideo.setFlag1(true)
                    closeComment(position)
                }
                R.id.video_star->{
                    ARouter.getInstance().build("/app/VideoDetailActivity").withSerializable("video",videoAdapter.data[position]).navigation()
                }
                R.id.comment_send_btn->{
                    //点击发送评论按钮
                    sendComment(position)
                }

            }
        }
        //点击评论上的控件，执行某些方法
        commentAdapter.addChildClickViewIds(R.id.comment_delete,R.id.comment_more,R.id.comment_huifu)
        commentAdapter.setOnItemChildClickListener { adapter, view, position ->
            when(view.id){
                R.id.comment_delete->{

                }
                R.id.comment_more->{
                    commentMore(position)
                }
                R.id.comment_huifu->{
                    //index  代表的当前视频的小标
                    //获取当前视频的et内容
                    val etSend =
                        videoAdapter.getViewByPosition(index, R.id.comment_send) as EditText
                    val toString = etSend.text.toString()
                    if(toString.isNotEmpty()){
                        val reply = Reply(0,commentAdapter.data[position].id,toString,DateTimeUtils.getDateTime(),0,"zhaolin",0,9697,"")

                        viewModel.sendIntent(VideoIntent.sendChildComment(reply))
                    }else{
                        ToastUtils.showLong("评论内容不能为空")
                    }
                }
            }
        }

    }

    private fun commentMore(position: Int) {
        //找到对应的子评论
        val recyclerView =
            commentAdapter.getViewByPosition(position, R.id.comment_reply) as RecyclerView
        val visible = recyclerView.isVisible
        if(visible){
            //可见状态
            recyclerView.isVisible = false
        }else{
            recyclerView.isVisible = true
        }
    }

    //发送评论
    private fun sendComment(position: Int) {
        //获取评论et的内容
        val etComment = videoAdapter.getViewByPosition(position, R.id.comment_send) as EditText
        val etText = etComment.text.toString()
        if(etText.isNotEmpty()){
            val sendComment = SendComment()
            sendComment.content = etText
            sendComment.itemid = videoAdapter.data[position].id
            sendComment.nickname = "zhaolin"
            sendComment.createtime = DateTimeUtils.getDateTime()
            viewModel.sendIntent(VideoIntent.sendComment(sendComment))
        }else{
            ToastUtils.showLong("评论内容不能为空")
        }
    }

    private fun closeComment(position:Int) {
        val ll_comment = videoAdapter.getViewByPosition(position, R.id.ll_comment) as LinearLayout
        ll_comment.isVisible = false
    }

    private fun openComment(position: Int) {
        val ll_comment = videoAdapter.getViewByPosition(position, R.id.ll_comment) as LinearLayout
        ll_comment.isVisible = true
        //请求评论列表
        val rvComment = videoAdapter.getViewByPosition(position, R.id.rv_comment) as RecyclerView
        rvComment.apply {
            adapter = commentAdapter
            layoutManager = LinearLayoutManager(requireContext())
        }
        viewModel.sendIntent(VideoIntent.getComment(0,videoAdapter.data[position].id.toString()))

    }

    private fun love(position: Int) {
        //判断是否能点赞了
        if(loveFlag){
            //取消点赞
            viewModel.sendIntent(VideoIntent.unAgree(agreeEntity))

        }else{
            //执行点赞
            val verifycode = videoAdapter.data[position].verifycode
            agreeEntity = AgreeEntity(DateTimeUtils.getDateTime(),0,verifycode,0,9697,"aaabbb")
            viewModel.sendIntent(VideoIntent.agree(agreeEntity))
        }
    }

    override fun initData() {
        lifecycleScope.launch {
            viewModel.uiState.collect{
                when(it){
                    is UiState.onSuccess<*> -> {
                        when(it.type){
                            HttpType.DEFAULT -> {
                                val entity = it.data as VideoEntity
                                videoAdapter.apply {
                                    if(page==1){
                                        data.clear()
                                    }
                                    data.addAll(entity)
                                    notifyDataSetChanged()

                                }
                            }
                            HttpType.DICT -> {
                                val entity = it.data as TypeEntity
                                typeAdapter.apply {
                                    data.clear()
                                    data.addAll(entity)
                                    notifyDataSetChanged()
                                }
                            }
                            HttpType.DETAIL->{
                                Log.d("sss", "initData: 已经点赞了")
                                //点赞了
                                agreeEntity = it.data as AgreeEntity
                                val imageView = videoAdapter.getViewByPosition(
                                    index,
                                    R.id.video_love
                                ) as ImageView
                                imageView.setImageResource(R.drawable.loved)
                                loveFlag = true
                            }
                            HttpType.AGREE->{
                                ToastUtils.showLong("点赞成功")
                                agreeEntity = it.data as AgreeEntity
                                viewModel.sendIntent(VideoIntent.insert(agreeEntity))
                                //修改图片  标志位更新
                                loveFlag = true
                                val imageView = videoAdapter.getViewByPosition(
                                    index,
                                    R.id.video_love
                                ) as ImageView
                                imageView.setImageResource(R.drawable.loved)
                            }
                            HttpType.UNAGREE->{
                                ToastUtils.showLong("取消点赞")
                                viewModel.sendIntent(VideoIntent.delete(agreeEntity))
                                //修改图片  标志位更新
                                loveFlag = false
                                val imageView = videoAdapter.getViewByPosition(
                                    index,
                                    R.id.video_love
                                ) as ImageView
                                imageView.setImageResource(R.drawable.baseline_favorite_border_24)
                            }
                            HttpType.COMMENT->{
                                val entity = it.data as CommentEntity
                                commentAdapter.apply {
                                    data.clear()
                                    data.addAll(entity)
                                    notifyDataSetChanged()
                                }
                            }
                            HttpType.SENDCOMMENT->{
                                ToastUtils.showLong("发送评论成功")
                                val entityItem = it.data as CommentEntityItem
                                commentAdapter.data.add(0,entityItem)
                                commentAdapter.notifyDataSetChanged()
                            }
                            HttpType.SENDCHILDCOMMENT->{
                                ToastUtils.showLong("回复评论成功")
                                viewModel.sendIntent(VideoIntent.getComment(0,videoAdapter.data[index].id.toString()))
                            }

                           else->{}
                        }
                    }
                    else->{
                        //ToastUtils.showLong("操作失败")
                    }
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode==100 && resultCode==Activity.RESULT_OK){
            val bean = data?.extras?.get(PictureSelector.PICTURE_RESULT) as PictureBean
            GlideUtils.loadCircle(requireContext(),bean.path,binding.iv)
        }
    }

}